package leetcode

//https://leetcode.com/problems/basic-calculator-ii/


fun main(args: Array<String>) {
    calculate("2 + 3 * 4 * 5")
}


fun calculate(s: String): Int {

    var res = 0

    val operator = ArrayList<Char>()

    val numbers = ArrayList<Int>()

    val numberBuf = StringBuffer()


    var i = 0
    while (i < s.length) {

        val c = s[i]
        when {
            c == '/' -> {
                val n = numbers.pop()
                var j = i + 1
                while (numberBuf.isEmpty() || s[j] in '0'..'9') {
                    if (s[j] in '0'..'9')
                        numberBuf.append(s[j])
                    else if (numberBuf.isNotEmpty())
                        break
                    j++
                }

                val m = numberBuf.toString().toInt()
                numberBuf.delete(0,numberBuf.length)


                numbers.push(n / m)

            }
            c == '*' -> {
                val n = numbers.pop()
                var j = i + 1
                while (numberBuf.isEmpty() || s[j] in '0'..'9') {
                    if (s[j] in '0'..'9')
                        numberBuf.append(s[j])
                    else if (numberBuf.isNotEmpty())
                        break
                    j++
                }

                val m = numberBuf.toString().toInt()
                numberBuf.delete(0,numberBuf.length)


                numbers.push(n * m)
            }
            c == '+' -> operator.push(c)
            c == '-' -> operator.push(c)
            c in '1'..'9' -> numberBuf.append(c)
        }

        if (c !in '1'..'9' && numberBuf.isNotEmpty()) {
            val num = numberBuf.toString().toInt()
            numbers.push(num)
            numberBuf.delete(0,numberBuf.length)
        }

        i++
    }
    return res
}